package io.renren.com.qywt.annotation;
import cn.hutool.core.util.ObjectUtil;
import io.renren.commons.security.user.UserDetail;
import io.renren.commons.tools.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class BeanUtils {
    public static<T> String getChangeFields(UserDetail userDetail,T newBean, T oldBean){
        List<Field> fields= Arrays.asList(newBean.getClass().getDeclaredFields());
        StringBuilder builder=new StringBuilder();
        builder.append("用户:").append(userDetail.getUsername()).append(";").append("操作时间:").append(DateUtils.format(new Date(),DateUtils.DATE_TIME_PATTERN)).append(";");
        for (Field field : fields) {
            field.setAccessible(true);
            if(field.isAnnotationPresent(ForUpdate.class)){
                try {
                    Object newValue=field.get(newBean);
                    Object oldValue=field.get(oldBean);
                    if(!ObjectUtil.equal(newValue,oldValue)){
                        builder.append("【").append(field.getAnnotation(ForUpdate.class).fieldName()).append("】").append(":");
                        builder.append("更改前:").append(oldValue);
                        builder.append(",");
                        builder.append("更改后:").append(newValue);
                        if(fields.indexOf(field)!=fields.size()-1){
                            builder.append(";");
                        }
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return builder.toString();
    }
}
